package com.qf.mybatis.utils;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;

/**
 * 避免重复创建
 * 1.在web环境使用该工具类，让每个线程调用getSession方法 能够获取该线程自己的sqlSession
 * 2.避免重复创建
 *
 * 对外提供什么呢？
 */
public class MybatisUtils {
    /**
     * SqlSessionFactory  工场类初始化
     */
    private static SqlSessionFactory sqlSessionFactory = null;
    /**
     * ThreadLocal对象  用于保存线程私有数据
     */
    private static ThreadLocal<SqlSession> threadLocal = new ThreadLocal<>();
    /*
     * 通过静态代码块初始化类级别的成员变量
     */
    static {
        InputStream inputStream;
        try {
            inputStream = Resources.getResourceAsStream("mybatis-config.xml");
            // 创建一个 SqlSessionFactoryBuilder对象
            SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
            // 利用 SqlSessionFactory 对象可以创建 Sqlsession对象
            sqlSessionFactory = sqlSessionFactoryBuilder.build(inputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    public static SqlSession getSqlSession() {
        //先检查当前线程是否获取过SqlSession对象,如果已经获取过，那直接使用
        SqlSession sqlSession = threadLocal.get();
        if (sqlSession!=null){
            return sqlSession;
        }
        //如果当前线程没有获取过SqlSession对象，那就创建一个新的sqlSession对象并且保存起来
        sqlSession = sqlSessionFactory.openSession();
        threadLocal.set(sqlSession);
        return sqlSession;
    }

    /**
     * 获得接口实现类Mapper
     *
     */
    public static <T> T getMapper(Class<T> clazz){
        SqlSession sqlSession = getSqlSession();
        return sqlSession.getMapper(clazz);
    }
    /**
     * 提交事务
     */
    public static void commit(){
        final SqlSession sqlSession = getSqlSession();
        //关闭当前线程的sqlSession对象
        sqlSession.commit();
        closeSqlSession();
    }

    public static void rollback(){
        final SqlSession sqlSession = getSqlSession();
        sqlSession.rollback();
        closeSqlSession();
    }


    public static void closeSqlSession() {
        final SqlSession sqlSession = getSqlSession();
        //threadLocal 清除曾经保存的sqlSession对象
        threadLocal.remove();
        //关闭线程对象
        sqlSession.close();
    }
}
